<html>
<head>

	<script src="config.js" type="text/javascript"></script> 
	<script src="jquery.js" type="text/javascript"></script> 
	<script>

		var notification;
		
		var unreadCounterTimer;
		var requestIteration = 0;
		var standardIdleTime = 4; // Seconds between iteration on unknown error
		var randomMemeTimer;
		var randomMeme;
		var showRandomMeme;
		// Time before Timeout.
		var requestTimeout = 1000 * 15;
		// Time between Random Meme calls.
		var randomMemeDelay = 1000 * 60 * 10;
				
		function init() { 
			// Initialize LogLevel
			if( !localStorage.logLevel )
				localStorage.logLevel = 0;
			logLevel = localStorage.logLevel;

			// Initialize Username
			if( !localStorage.username || localStorage.username == "" || localStorage.username === undefined ) {
				errorHandler( "Opt" );
				writeLog( "Username not set.", LOG_ERROR );
				return; }
				
			showRandomMeme = localStorage.showRandomMeme || "show";
			writeLog( "Random Meme behaviour: " + showRandomMeme, LOG_MOREINFO );
			
			// Using local variables from the localStorage.
			writeLog( "Setting Username as " + localStorage.username, LOG_MOREINFO )
			writeLog( "Setting Request Delay as " + localStorage.requestDelay, LOG_MOREINFO )

			// Checking Request Delay validity.
			if( isNaN( localStorage.requestDelay ) || localStorage.requestDelay < 30 ) {
				errorHandler( "Opt" );
				writeLog( "Request Delay value not in Range: " + requestDelay, LOG_ERROR );
				return; }
			
			// Getting Options
			notification = localStorage.notification;
			
			if( showRandomMeme == "show" )
				getRandomMeme();
			
			unreadCounter();
		}
		
		function checkConsistency() {
			var param
			var check = false;
			
			if( isNaN( param = localStorage.requestDelay ) || param < 30 )
				writeLog( "Request Delay value not in Range: " + localStorage.requestDelay, LOG_ERROR );

			else if( 	
					!( param = localStorage.username ) || 
					   param == "" || 
					   param === undefined || 
					   param == null 
				)
				writeLog( "Wrong username: \"" + localStorage.username + "\"", LOG_ERROR );
			
			else
				check = true;
			
			return check;
			
		}
		
		// Getting a Random Meme from the last 30 visualized on personal Timeline to show in Popup.
		function getRandomMeme() {
		
			if( checkConsistency() == false ) {
				errorHandler( "Opt" );
				return; }
		
		
			var page = getMeemiApi3Url( "wf/limit_30/html-json" );
		
			$.ajax({
				url: page,
				type: 'POST',
				timeout: requestTimeout,
				dataType: 'json',
				success: function( data ) {
				
					var badgeValue = 0;

					writeLog( "Retrieved Random Meme List", LOG_INFO );
					
					try {
						// Meemi can return also an error, in this case the error will be displayed
						if( data.error ) {
							writeLog( data.error.code, LOG_ERROR );
							chrome.browserAction.setBadgeText({ text: 'Err' });
							iterateRequest( getRandomMeme, requestTimeout, randomMemeDelay );
							}
						else {
							var randomNumber = Math.round( Math.random() * ( data.length -1 ));
							if( randomNumber < 0 )
								randomNumber = 0;
							randomMeme = data[randomNumber];
							
							writeLog( "Random number: " + randomNumber, LOG_MOREINFO );
							writeLog( "Random meme: " + JSON.stringify( randomMeme ), LOG_MOREINFO );

							iterateRequest( getRandomMeme, -1, randomMemeDelay );
						} }					

					// Check if something goes wrong.
					catch( exception ) {
						writeLog( "Unexpected error: " + exception, LOG_ERROR );
						iterateRequest( getRandomMeme, requestTimeout, randomMemeDelay );
						} },
				error: function( xhr, textStatus, thrownError ) {
					
					if( textStatus == "timeout" ) {
						writeLog( "Random Meme Timeout after " + requestTimeout / 1000 + " seconds.", LOG_WARNING );
						errorHandler( "TOut" ); }
					else {
						writeLog( "Errore: " + textStatus, LOG_ERROR );
						writeLog( "XMLHttpRequest: " + xhr.responseText, LOG_ERROR );
						}
					
					localStorage.lastError = textStatus;
					iterateRequest( getRandomMeme, standardIdleTime, randomMemeDelay );
				}    
			});
		
		}
		
		function errorHandler( badgeText ) {
			chrome.browserAction.setBadgeText({ text: badgeText });
		}
		
		function iterateRequest( iteratingFunction, timeDelay, functionDelay ) {
			timeDelay = timeDelay * 1000;
			if( timeDelay < 0 ) {
				requestIteration = 0;
				window.setTimeout( iteratingFunction, functionDelay ); }
			else {
				writeLog( "Requesting iteration: " + requestIteration, LOG_WARNING );
				requestIteration++;
				if( requestIteration <= 10 )
					window.setTimeout( iteratingFunction, timeDelay );
				else
					window.setTimeout( iteratingFunction, functionDelay );
				}
			
		}
		
		function unreadCounter() {
			
			if( !checkConsistency() ) {
				errorHandler( "Opt" );
				return; }
			
			page = getMeemiAPIURL('notify');
			
			parameters = {	meemi_id:localStorage.username,
					pwd:localStorage.password,
					app_key:applicationKey };

			// Setting request for notification.
			$.ajax({
				url: page,
				type: 'POST',
				data: parameters,
				timeout: requestTimeout,
				dataType: 'json',
				success: function( data ) {
				
					var badgeValue = 0;

					writeLog( "Retrieved Meme Counter", LOG_INFO );
					writeLog( JSON.stringify( data ), LOG_MOREINFO );
					
					try {
					
						// Meemi can return also an error, in this case the error will be displayed
						if( data.error ) {
							writeLog( data.error.code, LOG_ERROR );
							chrome.browserAction.setBadgeText({ text: 'Err' });
							iterateRequest( unreadCounter, requestTimeout, localStorage.requestDelay );
							}
						else {
							notification = JSON.parse( localStorage.notification );
							$.each( data, function( key, val ) {
								if( notification[key] ) {
									badgeValue += val;
								}
							});
							str = badgeValue == 0 ? '' : badgeValue.toString();
							chrome.browserAction.setBadgeText( {text: str} );
							localStorage.notificationCount = JSON.stringify( data );
							iterateRequest( unreadCounter, -1, localStorage.requestDelay );
						} }					

					// Check if something goes wrong.
					catch( exception ) {
						writeLog( "Unexpected error: " + exception, LOG_ERROR );
						iterateRequest( unreadCounter, requestTimeout, localStorage.requestDelay );
						} },
				error: function( xhr, textStatus, thrownError ) {
					
					if( textStatus == "timeout" ) {
						writeLog( "Unread Counter Timeout after " + requestTimeout / 1000 + " seconds.", LOG_WARNING );
						errorHandler( "TOut" ); }
					else {
						writeLog( "Errore: " + textStatus, LOG_ERROR );
						chrome.browserAction.setBadgeText({ text: 'Err' }); }
					
					localStorage.lastError = textStatus;
					iterateRequest( unreadCounter, standardIdleTime, localStorage.requestDelay );
				}    
			});
			
		}
		
		function getMeemiApi3Url( addings ) {
			var url = "http://meemi.com/api3/" +
				localStorage.username + "/" +
				addings;
			writeLog( "API3 URL requested: " + url, LOG_MOREINFO );
			return url;
		}

		function isMeemiUrl( url ) {
			return url.indexOf( "http://meemi.com/" ) == 0;
		}

		function getMeemiUrl( addings ) {
			var url = "http://meemi.com/" +
				localStorage.username + "/" +
				addings;
			return url;
		}
		
		chrome.extension.onRequest.addListener( function( request, sender, sendResponse ) {
			writeLog( "Request received by Background, validation: " + request.validation, LOG_INFO );
			if( request.validation == "random-meme" ) {
				writeLog( "Sending Random Meme to Popup", LOG_MOREINFO );
				sendResponse( randomMeme ); }; });
		
		function openMeemi( selectedTab ) {
			chrome.tabs.getAllInWindow( undefined, function( tabs ) {
				for( var i = 0, tab; tab = tabs[i]; i++ ) {
					if ( tab.url && isMeemiUrl( tab.url )) {
						chrome.tabs.update(tab.id, {selected: true});
						return;
					}
				}
				chrome.tabs.create({ url: getMeemiUrl( "wf" )});
			});
		}

		chrome.browserAction.onClicked.addListener( function( tab ) { openMeemi( tab ); });
	</script>
</head>
<body onload="init()">
</body>
</html>
